package com.happycat.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.happycat.base.R;
import com.happycat.base.exception.RestApiException;
import com.happycat.mapper.social.SocialVoiceRoomMapper;
import com.happycat.mapper.social.SocialVoiceRoomWheatMapper;
import com.happycat.mobile.model.UserAccount;
import com.happycat.mobile.service.UserAccountService;
import com.happycat.social.dto.SocialVoiceRoomWheatSaveDto;
import com.happycat.social.entity.SocialVoiceRoom;
import com.happycat.social.entity.SocialVoiceRoomWheat;
import com.happycat.social.service.ISocialVoiceRoomPermissionService;
import com.happycat.social.service.ISocialVoiceRoomWheatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 *
 * @author jsonbin
 * @date 2020-09-10
 */
@Service
public class SocialVoiceRoomWheatServiceImpl extends ServiceImpl<SocialVoiceRoomWheatMapper, SocialVoiceRoomWheat> implements ISocialVoiceRoomWheatService {
    @Autowired
    private SocialVoiceRoomMapper socialVoiceRoomMapper;
    @Autowired
    private UserAccountService userAccountService;
    @Autowired
    private ISocialVoiceRoomPermissionService socialVoiceRoomPermissionService;

    @Override
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public boolean del(String ids) {
        if(StrUtil.isBlank(ids)){
            throw new RestApiException(R.fail("参数为空"));
        }
        SocialVoiceRoomWheat wheat = getById(Long.parseLong(ids.split(",")[0]));
        if(wheat==null){
            throw new RestApiException(R.fail("麦位不存在"));
        }
        SocialVoiceRoom room = socialVoiceRoomMapper.selectById(wheat.getSvrId());

        if(!socialVoiceRoomPermissionService.hasRoomCreatorPermission(room)){
            throw new RestApiException(R.fail("无权操作"));
        }

        Arrays.stream(ids.split(",")).forEach(id -> {
            if(wheat.getForbid().equals("1")){
                throw new RestApiException(R.fail("麦位锁定，不可删除"));
            }
            if(wheat.getHostess().equals("1")){
                throw new RestApiException(R.fail("主持人位，不可删除"));
            }
            if(StrUtil.isNotBlank(wheat.getUserId())){
                throw new RestApiException(R.fail("麦位有人，不可删除"));
            }

            if(!removeById(id)){
                throw new RestApiException(R.fail("删除失败"));
            }
        });
        return true;
    }

    @Override
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public SocialVoiceRoomWheat add(SocialVoiceRoomWheatSaveDto socialVoiceRoomMemberSaveDto) {
        SocialVoiceRoom room = getSocialVoiceRoom(socialVoiceRoomMemberSaveDto.getSvrId());

        if(!socialVoiceRoomPermissionService.hasRoomCreatorPermission(room)){
            throw new RestApiException(R.fail("无权操作"));
        }

        SocialVoiceRoomWheat countWs = new SocialVoiceRoomWheat();
        countWs.setSvrId(socialVoiceRoomMemberSaveDto.getSvrId());
        countWs.setHostess("0");
        int count = count(new QueryWrapper<>(countWs));
        if(count>=8){
            throw new RestApiException(R.fail("麦位数量不得超过8个"));
        }
        //校验是否存在对应序号麦位
        SocialVoiceRoomWheat countWs2 = new SocialVoiceRoomWheat();
        countWs2.setSvrId(socialVoiceRoomMemberSaveDto.getSvrId());
        countWs2.setHostess("0");
        countWs2.setSort(socialVoiceRoomMemberSaveDto.getSort());
        int count2 = count(new QueryWrapper<>(countWs2));
        if(count2>=1){
            throw new RestApiException(R.fail("麦位序号不能重复"));
        }

        SocialVoiceRoomWheat wheat = BeanUtil.copyProperties(socialVoiceRoomMemberSaveDto, SocialVoiceRoomWheat.class);
        wheat.setRoomId(room.getRoomId());
        wheat.setHostess("0");
        wheat.setForbid("0");

        if(save(wheat)){
            return wheat;
        }else {
            throw new RestApiException(R.fail("新增失败"));
        }
    }

    private SocialVoiceRoom getSocialVoiceRoom(long svrId) {
        SocialVoiceRoom room = socialVoiceRoomMapper.selectById(svrId);
        if(room == null){
            throw new RestApiException(R.fail("房间不存在"));
        }
        if(!room.getAuditStatus().equals("1")){
            throw new RestApiException(R.fail("房间审核尚未通过"));
        }
        if(!room.getVisible().equals("1")){
            throw new RestApiException(R.fail("房间已被关闭"));
        }
        return room;
    }

    @Override
    public SocialVoiceRoomWheat lockOrRelease(Long id, Integer forbid) {
        SocialVoiceRoomWheat wheat = getById(id);
        if(wheat==null){
            throw new RestApiException(R.fail("麦位不存在"));
        }
        if(wheat.getHostess().equals("1")){
            throw new RestApiException(R.fail("主持人位,不可操作"));
        }
        SocialVoiceRoom room = getSocialVoiceRoom(wheat.getSvrId());

        if(!socialVoiceRoomPermissionService.hasRoomHostessPermission(room)){
            throw new RestApiException(R.fail("无权操作"));
        }

        if(forbid.intValue() == 1){
            //锁定
            if(wheat.getForbid().equals("1")){
                return wheat;
            }
            //校验麦位上是否有人
            if(StrUtil.isNotBlank(wheat.getUserId())){
                throw new RestApiException(R.fail("麦位有人，不可锁定"));
            }
            wheat.setForbid("1");
        }else if(forbid.intValue() == 2){
            //解锁
            if(wheat.getForbid().equals("0")){
                return wheat;
            }
            wheat.setForbid("0");
        }else {
            throw new RestApiException(R.fail("参数值非法"));
        }
        if(updateById(wheat)){
            return wheat;
        }else {
            throw new RestApiException(R.fail("操作失败"));
        }
    }

    @Override
    public SocialVoiceRoomWheat upOrDown(Long id, Long accountId, Integer upOrDown) {
        SocialVoiceRoomWheat wheat = getById(id);
        if(wheat==null){
            throw new RestApiException(R.fail("麦位不存在"));
        }
        if(wheat.getForbid().equals("1")){
            throw new RestApiException(R.fail("麦位被锁定，不可上麦"));
        }
        if(wheat.getHostess().equals("1")){
            throw new RestApiException(R.fail("主持人位,不可操作"));
        }
        SocialVoiceRoom room = getSocialVoiceRoom(wheat.getSvrId());

        if(!socialVoiceRoomPermissionService.hasRoomHostessPermission(room)){
            throw new RestApiException(R.fail("无权操作"));
        }

        if(upOrDown.intValue()==1){
            //上麦
            //校验麦位上是否有人
            if(StrUtil.isNotBlank(wheat.getUserId())){
                throw new RestApiException(R.fail("麦位有人，不可操作"));
            }
            //校验用户是否可用
            UserAccount userAccount = userAccountService.checkUserById(accountId);
            wheat.setAccountId(accountId);
            wheat.setUserId(userAccount.getImUserId());
        }else if(upOrDown.intValue()==2){
            //下麦
            wheat.setUserId(null);
            wheat.setAccountId(null);
        }else {
            throw new RestApiException(R.fail("参数值非法"));
        }
        if(updateById(wheat)){
            return wheat;
        }else {
            throw new RestApiException(R.fail("操作失败"));
        }
    }
}
